package com.ml.view;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.ml.app.MyApplication;
import com.ml.tools.BaseActivity;
import com.ml.tools.Utils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

public class MyChapo extends BaseActivity {
    RequestQueue mQueue = null;
    JsonObjectRequest mJsonObjectRequest = null;
    String sstr = "javascript:createChart([],[]);";
    private TextView bl;
    private TextView sl;
    private String ssl;
    private WebView web1;
    private TextView t;
    private String riqi, uu, yichangstr, lx;
    private boolean b = true;
    private final ArrayList<String> list = new ArrayList<String>();
    private final ArrayList<Integer> list1 = new ArrayList<Integer>();
    private final String url3 = MyApplication.SERVERPATH + "/Y502/TvgetTongji3";//uu=url3+"?riqi="+riqi+"&&name="+tt2;
    private final TextView[] text = new TextView[7];
    Handler mHander = new Handler() {
        public void handleMessage(Message msg) {
            try {
                switch (msg.what) {
                    case 1: {
                        JSONObject json = (JSONObject) msg.obj;
                        String re = json.getString("result");
                        String name = "";
                        if (re.equals("yes")) {

                            JSONArray array = json.optJSONArray("data");
                            if (array != null && array.length() > 0) {
                                String a = "[";
                                String b = "[";
                                list.clear();
                                list1.clear();
                                int znum = 0;
                                for (int i = 0; i < array.length(); i++) {
                                    if (!b.equals("[")) {
//                                        a += "',";
                                        b += ",";
                                    }
                                    JSONObject obj = array.optJSONObject(i);
                                    name = obj.getString("name");
                                    name = MyApplication.map.get(name);

                                    if (name == null) {
//                                        continue;
                                        name = MyApplication.map.get("未知");
                                    }

                                    int num = obj.getInt("num");
                                    list.add(name + " ("+ num + ")");
                                    list1.add(num);
                                    znum += num;
//                                    a += "'" + name;
                                    b += num;
                                }

                                for (int i = 0; i < list.size(); i++) {
                                    if (!a.equals("[")) {
                                        a += "',";
                                    }
                                    float bl = 0;
                                    if (znum > 0) {
                                        bl = list1.get(i) * 100.0f / znum;
                                    }
                                    String name1 = list.get(i) + " (" + String.format("%.2f", bl) + "%)";
                                    a += "'" + name1;
                                }

                                a += "']";
                                b += "]";
                                sstr = "javascript:createChart(" + a + "," + b + ");";
                                setdata();
                            } else {
                                list.clear();
                                list1.clear();
                                sstr = "javascript:createChart([],[]);";
                                setdata();
                            }
                        } else {
                            Toast.makeText(MyChapo.this, re, Toast.LENGTH_LONG).show();
                        }
                        break;
                    }
                }

            } catch (Exception e) {
                Toast.makeText(MyChapo.this, e.toString(), Toast.LENGTH_LONG).show();
            }
        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_second);
        riqi = MyApplication.riqi;
        yichangstr = MyApplication.map.get("yichang");
        setView();
        mQueue = MyApplication.getRequestQueue();
        new MyThread().start();
    }

    private void setView() {
        web1 = (WebView) findViewById(R.id.second_web1);
        t = (TextView) findViewById(R.id.second_t);
        text[0] = (TextView) findViewById(R.id.but4);
        text[1] = (TextView) findViewById(R.id.but5);
        text[2] = (TextView) findViewById(R.id.but6);
        text[3] = (TextView) findViewById(R.id.but7);
        text[4] = (TextView) findViewById(R.id.but8);
        text[5] = (TextView) findViewById(R.id.but9);
        text[6] = (TextView) findViewById(R.id.but10);
        web1.getSettings().setAllowFileAccess(true);
        web1.getSettings().setJavaScriptEnabled(true);
        t.setText(MyApplication.name2);
        web1.loadUrl("file:///android_asset/echart/index22.html");
        web1.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

                super.onPageStarted(view, url, favicon);
            }

            public void onPageFinished(WebView view, String url) {
                web1.loadUrl(sstr);
            }
        });
    }

    private void getData() {
        boolean isConnected = Utils.toastIsNetworkConnected(this);
        if (isConnected) {
            mJsonObjectRequest = new JsonObjectRequest(Request.Method.POST, uu,
                    null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    parseData(response);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
//		    	Toast.makeText(MyChapo.this,MyApplication.map.get("network_error_try_again"), Toast.LENGTH_LONG).show();
                }
            }
            );
            mQueue.add(mJsonObjectRequest);
        } else {
//					Toast.makeText(MyChapo.this,MyApplication.map.get("network_error_try_again"), Toast.LENGTH_LONG).show();

            return;
        }
    }

    protected void parseData(JSONObject response) {
        Message msg = mHander.obtainMessage();
        msg.what = 1;
        msg.obj = response;
        mHander.sendMessage(msg);
    }

    @Override
    protected void onDestroy() {
        b = false;
        super.onDestroy();
    }

    private void setdata() {
        for (int i = 0; i < list.size(); i++) {
            text[i].setVisibility(View.VISIBLE);
            text[i].setText(list.get(i) + ":" + list1.get(i));
        }
        for (int i = list.size(); i < 7; i++) {
            text[i].setVisibility(View.GONE);
        }
        web1.reload();
    }

    class MyThread extends Thread {
        int i = 0;

        @Override
        public void run() {
            try {
                lx = URLEncoder.encode(MyApplication.name, "UTF-8");
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
            uu = url3 + "?riqi=" + riqi + "&&name=" + lx;
            getData();
            while (b) {
                try {
                    Thread.sleep(1000);
                    i++;
                    if (i == 20) {
                        MyChapo.this.finish();
                        b = false;
                    }

                } catch (InterruptedException e) {

                }
            }
        }
    }

}
